import requests

from common.LoggerUtil import logger


class RequestsUtil:
    def get(self,url,params = None,**kw):
        try:
            res = requests.get(url,params=params,**kw)
        except Exception as e:
            #记录日志信息
            logger.error("访问不成功")
        else:
            return res

    def post(self,url,data = None,json = None,**kw):
        try:
            res = requests.post(url,data=data,json=json,**kw)
        except Exception as e:
            #记录日志信息
            logger.error("访问不成功")
        else:
            return res

    def visit(self, method, url, params = None, data = None, json=None, **kw):
        """访问接口"""
        if method.lower() == 'get':
            return self.get(url,params=params,**kw)
        elif method.lower() == 'post':
            return self.post(url,data=data,json=json,params=params,**kw)

    def json(self,method, url, params = None, data = None, json=None, **kw):
        """获取json数据"""
        res = self.visit(method, url, params=params, data=data, json=json, **kw)
        #获取json数据
        try:
            return res.json()
        except:
            #记录日志
            logger.error("不是json个格式数据")


class RequestsCookieUtil:
    def __init__(self):
        self.session = requests.Session()
    def get(self,url,params = None,**kw):
        try:
            res = self.session.get(url,params=params,**kw)
        except Exception as e:
            #记录日志信息
            logger.error("访问不成功")
        else:
            return res

    def post(self,url,data = None,json = None,**kw):
        try:
            res = self.session.post(url,data=data,json=json,**kw)
        except Exception as e:
            #记录日志信息
            logger.error("访问不成功")
        else:
            return res

    def visit(self, method, url, params = None, data = None, json=None, **kw):
        """访问接口"""
        if method.lower() == 'get':
            return self.get(url,params=params,**kw)
        elif method.lower() == 'post':
            return self.post(url,data=data,json=json,params=params,**kw)
        else:
            #requests通用方式
            return requests.request(method,url,data=data,json=json,params=params,**kw)

    def json(self,method, url, params = None, data = None, json=None, **kw):
        """获取json数据"""
        res = self.visit(method, url, params=params, data=data, json=json, **kw)
        #获取json数据
        try:
            return res.json()
        except:
            #记录日志
            logger.error("不是json个格式数据")


if __name__ == '__main__':
    r = RequestsUtil()
    res = r.json('post','http://120.78.128.25:8766/futureloan/member/login',data={'mobile_phone': '18311447530', 'pwd': '123456'})
    print(res)




